<?php
include('common/constants.php');
include('common/db.php');

if (!isset( $_POST )){
	echo "Nothing to save.";
}

//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_POST as $key => $input_arr) {
	$_POST[$key] = addslashes(htmlspecialchars($input_arr));
}

$slctSql = " SELECT * FROM user_preference where email='". $_POST['email']. "'";
$result = mysql_query($slctSql) or trigger_error(mysql_error());
$num = mysql_num_rows($result);

if ($num != 0) {
	//$updateSql = "UPDATE `user_preference` SET `email`='{$_POST['email']}', `origin`='{$_POST['origin']}', `destination`='{$_POST['destination']}', `travel_time`='" . date("H:i", strtotime($_POST['travel_time'])) . "', `vehicle_type_id`='{$_POST['vehicle_type_id']}' WHERE `email`='". $_POST['email']. "'";
	$updateSql = "UPDATE `user_preference` SET `email`='{$_POST['email']}', `origin`='{$_POST['origin']}', `destination`='{$_POST['destination']}' WHERE `email`='". $_POST['email']. "'";
	//echo $updateSql;
	if(mysql_query($updateSql)){
		echo "success";
	}else{
		echo "Failure while saving preferences.";
	}
	
}else if ($num == 0) {
	
	//$sql = "INSERT INTO `user_preference`(`email`, `origin`, `destination`, `travel_time`, `vehicle_type_id`) ";
	//$sql .= " VALUES('{$_POST['email']}', '{$_POST['origin']}', '{$_POST['destination']}', '" . date("H:i", strtotime($_POST['travel_time'])) . "', '{$_POST['vehicle_type_id']}');";
	
	$sql = "INSERT INTO `user_preference`(`email`, `origin`, `destination`) ";
	$sql .= " VALUES('{$_POST['email']}', '{$_POST['origin']}', '{$_POST['destination']}');";
	
	if(mysql_query($sql)){
			echo "success";
	}else{
		echo "Failure while saving preferences.";
	}
}